$(function () {
    util.common.search(); // add by aaron.wei 2018.12.17
    initTreeTable();
});

function initTreeTable() {
    var settings = {
        id: 'roleId',
        code: 'roleId',
        parentCode:'parentId',
        rootCodeValue: 1,//TODO modify the value by server
        url: ctx + "role/list",
        expandAll: true,
        expandColumn: 1,
        ajaxParams: {
        	roleName: $(".role-table-form").find("input[name='roleName']").val().trim()
        },
        columns: [{
        	field: 'selectItem',
            checkbox: true
        }, {
            field: 'roleName',
            width: 150,
            title: $MB.i18n('user.role')
        }, {
            field: 'remark',
            title: $MB.i18n('role.desc')
        }, {
            field: 'createTime',
            width: 150,
            align: 'center',
            title: $MB.i18n('common.crateTime')
        }]
    };

//    $MB.initTable('roleTable', settings);
    $MB.initTreeTable('roleTable', settings);
}

function search() {
	initTreeTable();
//    $MB.refreshTable('roleTable');
}

function refresh() {
    $(".role-table-form")[0].reset();
    search();
    $('#roleTree').jstree('destroy');
    createRoleTree();
}

function deleteRoles() {
//    var selected = $("#roleTable").bootstrapTable('getSelections');
    var selected = $("#roleTable").bootstrapTreeTable("getSelections");
    var selected_length = selected.length;
    if (!selected_length) {
        $MB.n_warning($MB.i18n('tips.del.role'));
        return;
    }
    var ids = "";
    for (var i = 0; i < selected_length; i++) {
        ids += selected[i].id;
        if (i !== (selected_length - 1)) ids += ",";
    }

    $MB.confirm({
        text: $MB.i18n('tips.del.role.confirm.msg'),
        confirmButtonText: $MB.i18n('del.confirm.btn'),
        cancelButtonText: $MB.i18n('del.confirm.cancle')
    }, function () {
        $.post(ctx + 'role/delete', {"ids": ids}, function (r) {
            if (r.code === 0) {
                $MB.n_success(r.msg);
                refresh();
            } else {
                $MB.n_danger(r.msg);
            }
        });
    });
}

function exportRoleExcel() {
    $.post(ctx + "role/excel", $(".role-table-form").serialize(), function (r) {
        if (r.code === 0) {
            window.location.href = "common/download?fileName=" + r.msg + "&delete=" + true;
        } else {
            $MB.n_warning(r.msg);
        }
    });
}

function exportRoleCsv() {
    $.post(ctx + "role/csv", $(".role-table-form").serialize(), function (r) {
        if (r.code === 0) {
            window.location.href = "common/download?fileName=" + r.msg + "&delete=" + true;
        } else {
            $MB.n_warning(r.msg);
        }
    });
}